from django.shortcuts import render
from .models import Prescription
import jwt
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework_simplejwt.tokens import RefreshToken
from datetime import datetime
from patient.models import Patient
from doctor.models import Doctor
from appointment.models import Appointment
from medicine_use.models import Medicine_use

from medicine.models import Medicine
import os
from django.utils.timezone import now
from django.conf import settings
# Create your views here.


class Get_All_All(APIView):
    permission_classes = [AllowAny]  # 允许任何人访问

    def get(self, request):
        try:
            prescriptions = Prescription.objects.filter(status="已完成").order_by('time')

        except Prescription.DoesNotExist:
            return Response({"error": "Prescription not found"}, status=500)

        if prescriptions:
            prescriptions_take_data = []
            prescriptions_untake_data = []
            for prescription in prescriptions:
                medicine_uses = Medicine_use.objects.filter(prescription_id=prescription.id)
                all_paid = all(
                    medicine_use.pay_status == "paid" or medicine_use.pay_status == "refund" for medicine_use in
                    medicine_uses)
                if all_paid:
                    if prescription.take_status == 'take':
                        prescription_data = {
                            'id': prescription.id,
                            'status': prescription.status,
                            'take_status': prescription.take_status,
                            'patient_id': prescription.patient_id.id,
                            'patient_name': prescription.patient_id.name,
                            'doctor_id': prescription.doctor_id.id,
                            'doctor_name': prescription.doctor_id.doctor_name,
                            'appointment': prescription.appointment.id,
                            'time': prescription.time,
                        }
                        prescriptions_take_data.append(prescription_data)
                        prescriptions_take_data.reverse()
                    else:
                        prescription_data = {
                            'id': prescription.id,
                            'status': prescription.status,
                            'take_status': prescription.take_status,
                            'patient_id': prescription.patient_id.id,
                            'patient_name': prescription.patient_id.name,
                            'doctor_id': prescription.doctor_id.id,
                            'doctor_name': prescription.doctor_id.doctor_name,
                            'appointment': prescription.appointment.id,
                            'time': prescription.time,
                        }
                        prescriptions_untake_data.append(prescription_data)
            return Response({'prescriptions_take': prescriptions_take_data,
                             'prescriptions_untake' : prescriptions_untake_data}, status=200)

        return Response({"error": "prescriptions not found"}, status=500)

class Get_All(APIView):
    permission_classes = [AllowAny]  # 允许任何人访问

    def get(self, request):
        patient_id = request.GET.get('patient_id')

        if not patient_id:
            return Response({"error": "patient_id is required"}, status=400)

        try:
            prescriptions = Prescription.objects.filter(patient_id=patient_id)
            prescriptions_data = list(prescriptions.values('id','description','time','status','patient_id','doctor_id','appointment'))
        except Prescription.DoesNotExist:
            return Response({"error": "Prescription not found"}, status=500)

        if prescriptions:
            return Response({'prescriptions': prescriptions_data}, status=200)

        return Response({"暂无处方"}, status=200)

class Get_Target(APIView):
    permission_classes = [AllowAny]  # 允许任何人访问

    def get(self, request):
        prescription_id = request.GET.get('prescription_id')

        if not prescription_id:
            return Response({"error": "prescription_id is required"}, status=400)

        try:

            prescription = Prescription.objects.get(id=prescription_id)
        except Prescription.DoesNotExist:
            return Response({"error": "prescription not found"}, status=500)

        if prescription:

            return Response({
                            'prescription_id': prescription.id,
                            'doctor_id': prescription.doctor_id.id,
                            'patient_id': prescription.patient_id.id,
                            'time': prescription.time,
                            'status': prescription.status,
                            'take_status': prescription.take_status,
                            'description': prescription.description,
                            'appointment_id': prescription.appointment.id,
                             }, status=200)

        return Response({"error": "prescription not found"}, status=400)

class Change(APIView):
    permission_classes = [AllowAny]  # 允许任何人访问

    def post(self, request):
        prescription_id = request.data.get('prescription_id')
        prescription_description = request.data.get('prescription_description')

        if not prescription_description:
            return Response({"error": "prescription_description is required"}, status=400)
        if not prescription_id:
            return Response({"error": "prescription_id is required"}, status=400)

        try:

            prescription = Prescription.objects.get(id=prescription_id)
        except Prescription.DoesNotExist:
            return Response({"error": "prescription not found"}, status=400)
        if prescription_id and prescription_description :
            prescription.description = prescription_description
            prescription.save()

            return Response({"message": "Success"}, status=200)
        return Response({"error": "Unsuccess"}, status=400)



class Create(APIView):
    permission_classes = [AllowAny]  # 允许任何人访问

    def post(self, request):

        prescription_patient_id = request.data.get('patient_id')
        prescription_doctor_id = request.data.get('doctor_id')
        prescription_appointment_id = request.data.get('appointment_id')

        patient_instance = Patient.objects.get(id=prescription_patient_id)
        doctor_instance = Doctor.objects.get(id=prescription_doctor_id)
        appointment_instance = Appointment.objects.get(id=prescription_appointment_id)

        if not prescription_patient_id:
            return Response({"error": "prescription_patient_id is required"}, status=400)
        if not prescription_doctor_id:
            return Response({"error": "prescription_doctor_id is required"}, status=400)
        if not prescription_appointment_id:
            return Response({"error": "appointment_id is required"}, status=400)

        if prescription_patient_id and prescription_doctor_id and prescription_appointment_id:
            prescription = Prescription(patient_id=patient_instance, doctor_id=doctor_instance,appointment=appointment_instance)
            prescription.save()
            return Response({"message": "创建成功"}, status=200)

        return Response({"error": "Unsuccess"}, status=400)

class Done(APIView):
    permission_classes = [AllowAny]  # 允许任何人访问

    def post(self, request):

        prescription_id = request.data.get('prescription_id')
        prescription_status = request.data.get('prescription_status')

        if not prescription_id:
            return Response({"error": "prescription_id is required"}, status=400)

        if not prescription_status:
            return Response({"error": "prescription_status is required"}, status=400)


        try:

            prescription = Prescription.objects.get(id=prescription_id)
            medicine_uses = Medicine_use.objects.filter(prescription_id=prescription_id)

        except Prescription.DoesNotExist:
            return Response({"error": "prescription or medicine_uses not found"}, status=500)
        if prescription_id and prescription_status:

            prescription.status = prescription_status
            prescription.save()
            for medicine_use in medicine_uses:
                medicine = Medicine.objects.get(id=medicine_use.medicine_id.id)
                if medicine_use.num > medicine.counts:
                    return Response({"error": "medicine not enough"}, status=500)
                else :
                    medicine.counts -= medicine_use.num
                    medicine.save()

            return Response({"message": "Success"}, status=200)
        return Response({"error": "Unsuccess"}, status=500)



# class Create(APIView):
#     permission_classes = [AllowAny]  # 允许任何人访问
#
#     def post(self, request):
#         apply_name = "123"
#         apply_position = "123"
#         apply_description = "123"
#
#         apply_patient_id = 1
#         apply_doctor_id = 1
#
#
#         if not apply_name:
#             return Response({"error": "apply_name is required"}, status=400)
#         if not apply_description:
#             return Response({"error": "apply_description is required"}, status=400)
#         if not apply_position:
#             return Response({"error": "apply_position is required"}, status=400)
#         if not apply_patient_id:
#             return Response({"error": "apply_patient_id is required"}, status=400)
#         if not apply_doctor_id:
#             return Response({"error": "apply_doctor_id is required"}, status=400)
#
#         if apply_position and apply_name and apply_doctor_id and apply_patient_id and apply_description:
#             Apply.objects.create(name=apply_name,
#                                  position=apply_position,
#                                  description=apply_description,
#                                  patient_id=apply_patient_id,
#                                  doctor_id=apply_doctor_id
#                                  )
#             return Response({"message": "创建成功"}, status=200)
#
#         return Response({"error": "Unsuccess"}, status=400)